// Author: Fadi Almasri //xample that demonstrates the use of for, while, and do-while loops. Each loop will perform the same task: printing the numbers from 1 to 5. I've included explanations in the comments. #include using namespace std; int main() { // Example using a for loop // The for loop is typically used when you know in advance how many times you want to execute a statement or a block of statements. //for (int i = 1; i <= 5; i++): This loop starts with i set to 1. It continues to run as long as i is less than or equal to 5, incrementing i by 1 after each iteration. //This is useful when you know how many times you need to execute the loop. cout << "Using for loop:" << endl; for (int i = 1; i <= 5; i++) { // Loop will run 5 times, printing the value of i each time cout << i << " "; } cout << endl; // Example using a while loop // The while loop is used when you want to repeat a block of code while a certain condition is true. //int j = 1; while (j <= 5): The loop starts with j set to 1. It checks the condition j <= 5 before each iteration, and as long as this condition is true, the loop continues to execute. //After each iteration, j is incremented. //Use a while loop when the number of iterations is not known beforehand and depends on some condition. cout << "Using while loop:" << endl; int j = 1; // Initialize the loop control variable while (j <= 5) { // Loop will run as long as j is less than or equal to 5 cout << j << " "; j++; // Increment the loop control variable } cout << endl; // Example using a do-while loop // The do-while loop is similar to the while loop, but it guarantees that the loop body is executed at least once, even if the condition is false initially. //int k = 1; do { ... } while (k <= 5): The loop starts with k set to 1. The body of the loop executes at least once before the condition k <= 5 is checked. //If the condition is true, the loop continues; otherwise, it stops. //Use a do-while loop when you want the loop body to execute at least once, regardless of the condition. cout << "Using do-while loop:" << endl; int k = 1; // Initialize the loop control variable do { // Loop will run at least once, printing the value of k cout << k << " "; k++; // Increment the loop control variable } while (k <= 5); // Continue looping as long as k is less than or equal to 5 cout << endl; return 0; }